import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import classnames from 'classnames'

export default function TextArea({ maxLength = 100, className, style, ...rest }) {
    // rest.value是回显的数据, 如果没有父组件没有指定回显数据, 默认给空
	const [value, setValue] = useState(rest.value || '')
	const textareaRef = useRef(null)

    const onChange = (e) => {
        setValue(e.target.value)

        /* if(rest.onChange) {
            rest.onChange(e.target.value)
        } */

        rest.onChange?.(e)
    }

	useEffect(() => {
		textareaRef.current.focus()
		// 调整textarea光标的位置
		textareaRef.current.setSelectionRange(-1, -1)
	}, [])

	return (
		<div className={styles.root}>
			<textarea
				ref={textareaRef}
				style={style}
				className={classnames('textarea', className)}
				maxLength={maxLength}
				{...rest}
                value={value}
                onChange={onChange}
			></textarea>

			<div className="count">
				{value.length}/{maxLength}
			</div>
		</div>
	)
}
